// Accordion.tsx
import React, {useEffect, useRef, useState} from "react";
import "./index.scss"; // 引入全局样式文件
import Return2Icon from "@src/assets/return2.svg?react"

interface AccordionProps {
    title: string;
    rightTitle?: React.ReactNode;
    active?: boolean;
    children: React.ReactNode;
}

//手风琴
const Accordion: React.FC<AccordionProps> = ({title, rightTitle, children, active = false}) => {
    const [isActive, setIsActive] = useState(active);
    const contentRef = useRef<HTMLDivElement>(null); // 创建一个 ref 来引用内容容器
    const [contentHeight, setContentHeight] = useState(0); // 动态存储内容高度

    const toggleAccordion = () => {
        setIsActive(!isActive);
    };
    useEffect(() => {
        // 在组件加载后，计算内容的实际高度
        if (contentRef.current) {
            setContentHeight(contentRef.current.scrollHeight);
        }
    }, [children]);
    return (
        <div className="accordion">
            <div className={isActive ? "active" : ""} onClick={toggleAccordion}>
                <div>
                    <Return2Icon></Return2Icon>
                    <p className="text-overflow-1">{title}</p>
                </div>
                <div>{rightTitle}</div>
            </div>
            <div className="panel" ref={contentRef} style={{maxHeight: isActive ? `${contentHeight}px` : "0"}}>
                {children}
            </div>
        </div>
    );
};

export default Accordion;